import {
  initArg, isYearReport, getPeriod, $ajax
} from './saas.utils.js';

// 汇算清缴
const HSQJ2013 = [
  // A10000
  5403, 5111, 222105, 5701,   
  // A101010
  5001, 5051, 5301, 530102, 530103, 530105, 530104, 530101,
  // A102010
  5401, 5402, 5711, 571102, 571106, 571109, 571110, 571108, 571103, 571104, 571101, 571105,
  // A104000
  560101, 560107, 560110, 560109, 560106, 560103, 560102, 560105, 560199, 5601, 560104, 
  560207, 560218, 560214, 560208, 560202, 560204, 560217, 560216, 560215, 560206, 560212, 560220, 560203, 560210, 560209, 560299, 5602,
  560303, 560305, 560302, 560304, 530101, 560301, 5603,
  // A105000
  571107, 560303, 571110, 560306,
  // A105050
  56020701, 56020702, 56020703, 56020704, 221101, 221103, 221106, 221104, 221105, 
  // A105060
  560107, 5001,
];
const HSQJ2007 = [
  // A10000
  6403, 6701, 6111, 222105, 6101,
  // A101010
  6001, 6051, 6301, 630101, 630102, 630104, 630103, 630105,
  // A102010
  6401, 6402, 6711, 671102, 671106, 671109, 671110, 671108, 671103, 671104, 671101,  671105, 
  // A104000
  660101, 660107, 660110, 660109, 660106, 660103, 660104, 660102, 660105, 660199, 6601, 
  660207, 660218, 660214, 660208, 660202, 660204, 660217, 660216, 660215, 660206, 660212, 660220, 660203, 660210, 660209, 660299, 6602,
  660303, 660305, 660302, 660304, 6603, 660301, 6603,

  // A105000
  660208, 660306, 671107, 671108, 671110, 660303,   
  // A105050
  66020701, 66020702, 66020703, 66020704, 221101, 221103, 221106, 221104, 221105    
];

console.log('saas page injected');

// 修改报税
let $oldTax = $('.old-tax')
let $handleTax = $('.js-handle-tax')
let html = '<a href="javascript:;" class="js-handle-tax">' + $handleTax.html() + '</a>';
$oldTax.before(html);
$handleTax.remove();

window.addEventListener(
  'message',
  function({ data }) {
    if (data.event === 'getSaasData') {
      getSaasData(data.data, postDataBack);
    }
    if (data.event === 'taxCompletion') {
      changeState(data, function(res) {
        window.postMessage(
          {
            event: 'taxCompletionDone',
            data: res
          },
          '*'
        );
      });
    }
    if (data.event === 'refreshPage') {
      window.location.reload();
    }
    if (data.event === 'syncReportInfoInSaas') {
      syncReportInfoInSaas(data.data);
    }
    if (data.event === 'syncReportInSaas') {
      syncReportInSaas(data.data);
    }
  },
  false
);

// 一键报税点击逻辑
$('body').on('click', '.js-handle-tax', function() {
  $ajax('/api/index/queryTax', {}).then(res => {
    if (res.success) {
      let companyInfo = window.renderData.accBook;
      let curPeriodStatus = res.curPeriodStatus; // 会计期间的状态(0-未结账 2-已结账 3-已结帐且已报税)
      // 未结账不打开
      let canTaxObj = { canTax: true };
      // if (curPeriodStatus === 0) {
      //   let currStatus = $('.status-step').find('.curr');
      //   if (currStatus.length > 0) {
      //     let errMsg = '当前期间未结账，请先结账';
      //     alert(errMsg);
      //     return;
      //   }
      //   canTaxObj = { canTax: false };
      // } else if (curPeriodStatus === 3) {
      //   canTaxObj = { canTax: false };
      // } else {
      //   canTaxObj = { canTax: true };
      // }
      companyInfo = Object.assign({}, companyInfo, res.data, canTaxObj);
      companyInfo.curYear = window.renderData.year;
      companyInfo.curPeriod = window.renderData.period;
      companyInfo.pagePath = window.location.href;
      companyInfo.useOneClickNum = 0; // 点击次数
      window.postMessage(
        {
          event: 'setBaseInfo',
          data: companyInfo
        },
        '*'
      );
    } else {
      alert('获取报税基本信息失败，请稍候再试！');
    }
  });
});

// ajax methods
const getSaasData = function(paramData, callBack) {
  if (typeof callBack !== 'function') {
    alert('别乱来！要传回调函数！');
    return;
  }
  let type = paramData.type;
  if (type === 'zzs') {
    getAccount(paramData, callBack);
  } else if (type === 'hsqj') {
    getAmt(paramData, callBack);
  } else {
    queryReportData(paramData, callBack);
  }
};

/*
 * 获取财务报表
 * */
let queryReportData = async function(paramData, callBack) {
  let type = paramData.type;
  let startTime = paramData.startTime;
  let endTime = paramData.endTime;
  let year = startTime.substr(0, 4);
  let beginPeriod = Number.parseInt(startTime.substr(5));
  let endPeriod = Number.parseInt(endTime.substr(5));
  let isYearReportBoolean = isYearReport(startTime, endTime, type);

  // 资产负债表无季报
  // if (type === 'balance') {
  //   beginPeriod = endPeriod;
  // }

  // 接口报表类型
  let interfaceTypeObj = {
    balance: 'RptBalanceSheet',
    cash: 'RptCashing',
    profit: 'RptProfit',
    sds: 'RptProfit'
  };

  let saasParams = {
    reportType: type === 'all' ? 'bRptBalanceSheet' : interfaceTypeObj[type], // all 代表导出申报，设置reportType 为默认bRptBalanceSheet
    year: year,
    beginPeriod: beginPeriod,
    endPeriod: endPeriod,
    queryAll: true
  };
  if (paramData.isClassify) {
    saasParams.isClassify = 1;
  } else {
    saasParams.isClassify = 0;
  }

  let subjectData;
  saasParams = initArg(paramData, saasParams);
  if (
    saasParams.openParams.inputData.institution
    !== saasParams.openParams.taxInfo.institution
  ) {
    subjectData = await getGDZC(paramData);
  }
  let url = '/api/index/queryReportData';
  let newCitys = ['重庆', '广西'];
  if (paramData.cityName && newCitys.find(item => paramData.cityName.includes(item))) {
    url = '/api/index/queryReportDataNew';
  }
  $ajax(url, saasParams).then(res => {
    if (res.success) {
      res.data.openParams.inputData.data.subject = subjectData;
      // 零申报
      if (paramData.zero) {
        let cash = res.data.openParams.inputData.data.cash;
        res.data.openParams.inputData.data.cash = cash.map(item => {
          item.colValue1 = '0.00';
          item.colValue2 = '0.00';
          item.colValue3 = '0.00';
          return item;
        });
      }
      typeof callBack === 'function'
        && callBack({
          data: res.data,
          sheetType: 'cwbb',
          sheet: type,
          isYearReport: isYearReportBoolean,
          success: true
        });
    } else {
      callBack({ success: false, data: 'saas系统请求数据异常！' });
      console.error(res);
    }
  });
};

/*
 * 获取增值税
 * */
let getAccount = function(paramData, callBack) {
  let period = getPeriod();

  let saasParams = {
    subjectCodes: [500101, 500102, 222101, 222118, 1601, 1602],
    year: period.curYear,
    beginPeriod: period.start,
    endPeriod: period.end
  };

  $ajax('/api/index/querySubjectHappens', initArg(paramData, saasParams)).then(
    res => {
      callBack({
        data: res,
        sheetType: 'zzs',
        sheet: 'zzs',
        success: true
      });
    }
  );
};

/**
 *  获取固定资产（当制度转换的时候）
 * @param paramData
 * @returns {Promise}
 */
const getGDZC = function(paramData) {
  return new Promise(resove => {
    let period = getPeriod();
    let start = period.start >= 10 ? period.start : 0 + period.start;
    let end = period.end >= 10 ? period.end : 0 + period.end;
    let saasParams = {
      period_q: `${period.curYear}-${start}`,
      period_z: `${period.curYear}-${end}`,
      subjectLevel: -1,
      subjectType: 1,
      currencyCode: 'all'
    };
    $ajax('/api/books/subject/getList', initArg(paramData, saasParams)).then(
      res => {
        if (res.success) {
          let data = res.data || [];
          data = data.filter(d => {
            return d.subjectCode === '1601' || d.subjectCode === '1602';
          });
          resove(data);
        }
      }
    );
  });
};

/*
 * 获取汇算清缴相关信息 ins = 税局制度 institutionCode = saas制度
 * */
const getAmt = function(paramData, callBack) {
  let { type, startTime, taxInfo } = paramData;
  let subjectCodes = [];
  let institutionCode = window.renderData.accBook.institutionCode;

  if (taxInfo.isHsqjSmall) {
    // 如果是小微企业汇算清缴，则变更type
    paramData.type = 'hsqj-small';
    type = 'hsqj-small';
  }
  const insType = institutionCode === '1' ? '2007' : '2013';
  // 税局中一般和小规模的汇算清缴的表是一致的，取数是根据saas中的制度来，所以这里修改税局制度为saas制度
  paramData.ins = insType;

  if (type === 'hsqj-small') {
    if (insType === '2007') {
      subjectCodes = HSQJ2007;
    } else {
      subjectCodes = HSQJ2013;
    }
  } else if (insType === '2007') {
    subjectCodes = HSQJ2007;
  } else {
    subjectCodes = HSQJ2013;
  }
  let saasParams = {
    subjectCodes: subjectCodes,
    year: parseInt(startTime.substr(0, 4))
  };

  $ajax('/api/index/queryAmt', initArg(paramData, saasParams)).then(res => {
    if (res.success) {
      // 对数据进行包装 open解析需要
      const hsqjData = res.data.openParams.inputData.data;
      res.data.openParams.inputData.data = { [type]: hsqjData };
      callBack({
        data: res.data,
        insType,
        sheetType: type, // hsqj hsqj-small
        type,
        sheet: type,
        isHSQJ: true,
        success: true
      });
    } else {
      callBack({ success: false, data: 'saas系统请求数据异常！' });
      console.error(res);
    }
  });
};

/**
 * 更改报税状态
 * @param callBack
 */
const changeState = async (data, callBack) => {
  data = data.data;
  let taxSource = 2;
  if (!data.isSupport) {
    taxSource = 3;
  }
  if (data.useOneClickNum == 0) {
    taxSource = 3;
  }
  console.log(taxSource, data.countyName, data.version, data.useOneClickNum);
  // 季报时 3 6 9 12月判断
  // 月报时 每月判断
  // 重庆自营 2019-08及之后账期才做同步
  const isSynced = await canSyncReportInSaas();
  // const isNeedSync = [500000].includes(window.renderData.deptCityId) && ((!isSynced
  //     && [3, 6, 9, 12].includes(+window.renderData.period)
  //     && window.renderData.accBook.taxReportType === 'QUARTER')
  //     || (window.renderData.accBook.taxReportType === 'MONTH' && !isSynced))
  //   // eslint-disable-next-line no-undef
  //   && moment(getAccountYearPeriod()).isAfter('2019-07', 'month');
  if (false) {
    callBack({ success: false, data: '申报失败，请先同步申报表' });
    return;
  }
  $ajax('/api/index/reportTax', {
    taxUserId: window.renderData.userId,
    taxUser: window.renderData.userName,
    taxSource: taxSource,
    taxCity: data.countyName,
    taxClientVersion: data.version
  }).then(res => {
    callBack(res);
  });
};

const postDataBack = data => {
  console.log('请求saas数据成功');
  window.postMessage(
    {
      event: 'getSaasDataDone',
      data: data
    },
    '*'
  );
};

const getAccountYearPeriod = () => {
  const { year, period } = window.renderData;
  return year + '-' + (period.length > 1 ? period : `0${period}`);
};

const syncReportInfoInSaas = data => {
  console.log('收到', data);
  let result = '同步申报种类成功';
  let typeList = data.syncReportInfo.map(item => ({
    ...item,
    // eslint-disable-next-line
    declareTime: item.declareTime ? item.declareTime : new moment().format('YYYY-MM-DD HH:mm:ss'),
    accountYearPeriod: getAccountYearPeriod()
  }));
  $ajax('/api/declaration/saveRecordTypeList', {
    typeList
  }).then(res => {
    if (!res.success) {
      result = `同步申报种类失败, ${res.description || res.data}`;
    }
    window.postMessage(
      {
        event: 'syncReportInfoInSaasBack',
        message: result
      },
      '*'
    );
  });
};

const canSyncReportInSaas = () => {
  return new Promise((resolve, reject) => {
    $ajax('/api/declaration/queryRecordListByAccBookId', {
      accountYearPeriod: getAccountYearPeriod()
    }).then(res => {
      resolve(res.success && res.data && res.data.length);
    });
  });
};

const syncReportInSaas = async data => {
  console.log('收到', data);
  let result = '同步申报表成功';
  const canSync = await canSyncReportInSaas();
  if (!canSync) {
    result = '请先同步申报种类！';
    window.postMessage(
      {
        event: 'syncReportInSaasBack',
        message: result
      },
      '*'
    );
    return;
  }
  $ajax('/api/declaration/saveRecord', {
    ...data,
    detail: JSON.stringify(data.detail),
    accountYearPeriod: getAccountYearPeriod()
  }).then(res => {
    if (!res.success) {
      let errMsg = res.description || res.data;
      errMsg === '数据异常'
        && (errMsg = '当前申报种类中无此报表，请核实后再行同步');
      result = `同步申报表失败, ${res.description || res.data}`;
    }
    window.postMessage(
      {
        event: 'syncReportInSaasBack',
        message: result
      },
      '*'
    );
  });
};

